//
//  XMLParser.m
//  xmldemo
//
//  Created by fangdi on 09-9-14.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "XMLParser.h"


@implementation XMLParser

-(id)initWithContentsOfFile:(NSString *)filePath{
	if((self = [super init]) != nil){
		isRoot = YES;
		stack = [[Stack alloc] init];
		document = [[XMLDocument alloc] init];
		parser = [[NSXMLParser alloc] initWithData:[[NSData alloc] initWithContentsOfFile:filePath]];
		[parser setDelegate:self];
		return self;
	}
	return nil;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
	XMLNode *node = [[XMLNode alloc] init];
	node.name = elementName;
	NSEnumerator *keyEnum = [attributeDict keyEnumerator];
	id key;
	while(key = [keyEnum nextObject]){
		XMLAttribute *attribute = [[XMLAttribute alloc] init];
		attribute.name = (NSString *)key;
		attribute.value = (NSString *)[attributeDict objectForKey:key];
		[node.attributes addObject:attribute];
		[attribute release];
	}
	if(isRoot){
		document.root = node;
		isRoot = NO;
	}else{
		//含有父节点
		XMLNode *parent = (XMLNode *)[stack getLast];
		node.parent = parent;
		[parent.children addObject:node];
	}
	[stack push:node];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	XMLText *text = [[XMLText alloc] init];
	text.text = string;
	XMLNode *currentNode = (XMLNode *)[stack getLast];
	currentNode.text = text;
	[text release];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	XMLNode *node = (XMLNode *)[stack getLast];
	[node release];
}

-(XMLDocument *)getDocument{
	if([parser parse]){
		return document;	
	}
	return nil;
}

-(void)dealloc{
	[stack release];
	[document release];
	[parser release];
	[super dealloc];
}
@end
